#!/bin/bash
# server install

SCRIPT=`readlink -f "$0"`
P=`dirname "$SCRIPT"` # $P/$0
#cd $P

SERVERDIR="$P/server"
GMDIR="$P/gm"


#$GMDIR/lsfrcc.sh $*

if [ $? -ne 0 ]
then
  exit 1
fi

for i in `cat $GMDIR/states.txt`
do
  NAME=`echo $i | awk -F':' '{print $1}'`
  PORT=`echo $i | awk -F':' '{print $3}'`

  # gm
  mkdir -pv $SERVERDIR/$NAME/gamemodes

  if [ -d $GMDIR/$NAME ]
  then
    cp -uv $GMDIR/$NAME/*.amx $SERVERDIR/$NAME/gamemodes/
    #cp -uv $GMDIR/*.pwn $SERVERDIR/$NAME/gamemodes/
  fi

  # fs
  mkdir -pv $SERVERDIR/$NAME/filterscripts
  cp -uv $P/fs/*.amx $SERVERDIR/$NAME/filterscripts/ 2> /dev/null
  
  # config  
  echo "# Auto-generated file. Do not edit" > $SERVERDIR/$NAME/server.cfg
  if [ -r $P/data/server.cfg ]
  then
    #awk  '/^[a-z_]+ ([a-z_A-Z0-9.]+ ?)+/ {print $0}' \
    #  $P/data/server.cfg  >> $SERVERDIR/$NAME/server.cfg # ignore comments and empty lines
    gcc -E -P -x c -DPORT=$PORT -DNAME=$NAME -DREV=`svnversion -n $P` $P/data/server.cfg | sed '/^$/d' >> $SERVERDIR/$NAME/server.cfg
  fi
  #echo "port $PORT" >> $SERVERDIR/$NAME/server.cfg

  # plugins
  mkdir -pv $SERVERDIR/$NAME/plugins
  for j in `ls $P/plugins/`
  do
    if [ "$j" != "SDK" ]
    then
      cp -uvf $P/plugins/$j/*.so $SERVERDIR/$NAME/plugins/ 2> /dev/null
    fi
  done

  # scriptfiles
  mkdir -pv $SERVERDIR/$NAME/scriptfiles/users
  if [ -d $P/data/scriptfiles/$NAME ]
  then
    mkdir -pv $SERVERDIR/$NAME/scriptfiles/$NAME
    #cp -uvr $P/data/scriptfiles/$NAME/[!.]* $SERVERDIR/$NAME/scriptfiles/$NAME/
    rsync -r --exclude=.svn $P/data/scriptfiles/$NAME/ $SERVERDIR/$NAME/scriptfiles/$NAME/
  fi


done

# clean
#rm -rfv `find $SERVERDIR -name '.svn'`


